import { useState } from 'react'
import { Button } from '@/components/ui/button'
import type { DateRange } from 'react-day-picker'
import { Download } from 'lucide-react'
import { toast } from 'sonner'
import { format } from 'date-fns'

interface FunnelData {
  totalUsers: number
  activeUsers: number
  paidUsers: number
  date: string
}

export default function UserFunnelAnalysis({
  timeRange,
  dateRange
}: {
  timeRange: string
  dateRange?: DateRange
}) {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<FunnelData[]>([])
  const [timeDescription, setTimeDescription] = useState('')

  // 格式化数字
  const formatNumber = (num: number) => {
    return new Intl.NumberFormat().format(num)
  }

  // 计算转化率
  const calculateRate = (current: number, total: number) => {
    if (total === 0) return '0%'
    return `${((current / total) * 100).toFixed(2)}%`
  }

  // 获取表格数据
  const getTableData = () => {
    if (!data) return []

    const totals = {
      totalUsers: data.reduce((sum: number, item: FunnelData) => sum + item.totalUsers, 0),
      activeUsers: data.reduce((sum: number, item: FunnelData) => sum + item.activeUsers, 0),
      paidUsers: data.reduce((sum: number, item: FunnelData) => sum + item.paidUsers, 0)
    }

    return [{
      date: timeDescription,
      ...totals,
      activeRate: calculateRate(totals.activeUsers, totals.totalUsers),
      paidRate: calculateRate(totals.paidUsers, totals.activeUsers)
    }]
  }

  // 下载数据
  const handleDownload = () => {
    if (!dateRange?.from || !dateRange?.to) {
      toast.error('请选择日期范围')
      return
    }

    const startDate = format(dateRange.from, 'yyyy-MM-dd')
    const endDate = format(dateRange.to, 'yyyy-MM-dd')
    const params = new URLSearchParams({
      startDate,
      endDate
    })

    window.open(`/api/user-funnel/export?${params}`, '_blank')
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <Button
          variant="outline"
          size="sm"
          onClick={handleDownload}
          className="flex items-center gap-2"
        >
          <Download className="w-4 h-4" />
          导出数据
        </Button>
      </div>
      <div className="border rounded-lg">
        <table className="w-full">
          <thead>
            <tr className="border-b bg-gray-50">
              <th className="text-left p-4">日期</th>
              <th className="text-right p-4">总用户数</th>
              <th className="text-right p-4">活跃用户数</th>
              <th className="text-right p-4">活跃转化率</th>
              <th className="text-right p-4">付费用户数</th>
              <th className="text-right p-4">付费转化率</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={6} className="text-center py-4">
                  <div className="flex items-center justify-center">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                  </div>
                </td>
              </tr>
            ) : getTableData().map((row, index) => (
              <tr key={index} className="border-b">
                <td className="p-4">{row.date}</td>
                <td className="text-right p-4">{formatNumber(row.totalUsers)}</td>
                <td className="text-right p-4">{formatNumber(row.activeUsers)}</td>
                <td className="text-right p-4">{row.activeRate}</td>
                <td className="text-right p-4">{formatNumber(row.paidUsers)}</td>
                <td className="text-right p-4">{row.paidRate}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
} 